/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.group;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.core.Group;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.service.core.RoleManager;
import com.blandware.atleap.service.core.GroupManager;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.SelectRolesForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.acegi.UserManagerDaoImpl;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.*;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>Assigns Roles to Group
 * </p>
 * <p><a href="AssignGroupRolesAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.3 $ $Date: 2006/03/25 11:27:52 $
 * @struts.action path="/core/group/assignRoles"
 * name="selectRolesForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-group-assignRoles"
 * @struts.action-forward name="inputForward"
 * path=".core.group.assignRoles"
 * @struts.action-forward name="viewGroup"
 * path="/core/group/view.do"
 * redirect="true"
 * @struts.action-forward name="listGroups"
 * path="/core/group/list.do"
 * redirect="true"
 * @struts.action-forward name="callAssignRoles"
 * path="/core/group/callAssignRoles.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/group/list.do"
 */
public final class AssignGroupRolesAction extends BaseAction {
    /**
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are proceeding
     * @param response The HTTP response we are creating
     * @return an ActionForward instance describing where and how
     *         control should be forwarded, or null if response
     *         has already been completed
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {

        if ( !isCancelled(request) ) {

            String groupName = (String) request.getSession().getAttribute(WebappConstants.GROUP_NAME_KEY);
            if ( GenericValidator.isBlankOrNull(groupName) ) {
                if ( log.isWarnEnabled() ) {
                    log.warn("Missing group name. Returning to list...");
                }
                return mapping.findForward("listGroups");
            }

            // acquire POJOs for all selected roles
            RoleManager roleManager = (RoleManager) getBean(Constants.ROLE_MANAGER_BEAN);
            SelectRolesForm selectRolesForm = (SelectRolesForm) form;
            String[] selectedRoleNames = selectRolesForm.getSelectedRoles();

            List roles = new ArrayList();
            for ( int i = 0; i < selectedRoleNames.length; i++ ) {
                String roleName = selectedRoleNames[i];
                Role role = roleManager.retrieveRole(roleName);
                if ( role != null ) {
                    roles.add(role);
                }
            }

            // update group roles
            GroupManager groupManager = (GroupManager) getBean(Constants.GROUP_MANAGER_BEAN);
            Group group = groupManager.retrieveGroup(groupName);

            if ( group == null ) {
                // group not found. it might be deleted by someone else
                ActionMessages errors = new ActionMessages();
                errors.add("groupNotFound", new ActionMessage("core.group.errors.notFound"));
                saveErrors(request, errors);
                return mapping.findForward("listGroups");
            }

            group.setVersion(Long.valueOf(selectRolesForm.getVersion()));

            UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
            Set touchedUsers = new HashSet();

            // remove roles which were unselected
            // list of roles is copied in order to prevent ConcurrentModificationException to be thrown
            List groupRoles = new ArrayList(group.getRoles());
            for ( int i = 0; i < groupRoles.size(); i++ ) {
                Role role = (Role) groupRoles.get(i);
                if ( !roles.contains(role) ) {
                    group.removeRole(role);
                    List groupUsers = group.getUsers();
                    for (int j = 0; j < groupUsers.size(); j++) {
                        User user = (User) groupUsers.get(j);
                        user.removeRole(role, group);
                        touchedUsers.add(user);
                    }
                }
            }
            // add new roles
            for ( Iterator i = roles.iterator(); i.hasNext(); ) {
                Role role = (Role) i.next();
                group.addRole(role);
                List groupUsers = group.getUsers();
                for (int j = 0; j < groupUsers.size(); j++) {
                    User user = (User) groupUsers.get(j);
                    user.addRole(role, group);
                    touchedUsers.add(user);
                }
            }

            UserManagerDaoImpl userManagerDaoImpl = (UserManagerDaoImpl) getBean(Constants.USER_DETAILS_SERVICE_BEAN);

            try {
                groupManager.updateGroup(group);
                for (Iterator i = touchedUsers.iterator(); i.hasNext();) {
                    User user = (User) i.next();
                    userManager.updateUser(user);

                    if (user.getName().equals(request.getRemoteUser())) {
        	            userManagerDaoImpl.updateUser(user);
                    }
                }
            } catch ( ObjectOptimisticLockingFailureException e ) {
                // group was updated or deleted by another transaction
                ActionMessages errors = new ActionMessages();
                errors.add("updateFailed", new ActionMessage("core.group.errors.updateFailed"));
                saveErrors(request, errors);
                request.setAttribute(WebappConstants.GROUP_NAME_KEY, groupName);
                return mapping.findForward("callAssignRoles");
            }

            // flush CP cache to avoid a situation when user permissions for
            // CP menu items are changed but he/she still obtains cached version
            // of page
            CacheUtil cacheUtil = CacheUtil.getInstance(request);
            cacheUtil.flushContentPageCache();
        }
        return mapping.findForward("listGroups");
    }
}